package xcore

import (
	"context"
	"errors"
	"gitee.com/xfrm/middleware/xlog"
	"reflect"
)

func ToInterfaceSlice(ctx context.Context, arr interface{}) ([]interface{}, error) {
	if arr == nil {
		return nil, nil
	}
	v := reflect.ValueOf(arr)
	if v.Kind() != reflect.Slice {
		return nil, errors.New("not a slice")
	}
	l := v.Len()
	ret := make([]interface{}, l)
	for i := 0; i < l; i++ {
		ret[i] = v.Index(i).Interface()
	}
	return ret, nil
}
func ToInterfaceSliceNilWhenError(ctx context.Context, arr interface{}) []interface{} {
	slice, err := ToInterfaceSlice(ctx, arr)
	if err != nil {
		xlog.Infof(ctx, "convert interface slice error:%v", err)
		return nil
	}
	return slice
}
